<template>
  <!-- 页面结构保持不变 -->
  <view class="setting-page">
    <!-- 位置追踪核心模块 -->
    <view class="location-upload-module" style="display: block !important;">
      <view class="action-btn" @click="toggleTracking">
        <button :class="isTracking ? 'btn-stop' : 'btn-start'">
          {{ isTracking ? '停止追踪' : '开始追踪' }}
        </button>
      </view>

      <view 
        class="status-tip" 
        :class="status === 'success' ? 'tip-success' : (status === 'error' ? 'tip-error' : (status === 'warning' ? 'tip-warning' : 'tip-info'))"
      >
        {{ statusTip || '等待操作...' }}
      </view>

      <view class="location-info">
        <view>当前经纬度：{{ currentLocation?.lng?.toFixed(6) || '未获取' }}, {{ currentLocation?.lat?.toFixed(6) || '未获取' }}</view>
        <view>解析地址：{{ currentLocation?.address || '未解析' }}</view>
        <view>定位精度：{{ currentLocation?.accuracy || '--' }} 米</view>
        <view>与上次距离：{{ lastDistance ? lastDistance.toFixed(1) + ' 米' : '首次定位' }}</view>
        <view>最后更新：{{ lastUpdateTime || '未更新' }}</view>
        <view>上传状态：{{ uploadStatus || '未上传' }}</view>
      </view>

      <!-- 历史记录区域 -->
      <view class="history-header">
        <view class="history-title">位置历史</view>
        <button 
          class="clear-all-btn" 
          @click="clearAllHistory" 
          v-if="uploadHistory.length > 0"
        >
          清空记录
        </button>
      </view>
      
      <view v-if="uploadHistory.length === 0" class="empty-history">暂无历史记录</view>
      
      <view 
        class="history-item" 
        v-for="(item, index) in uploadHistory" 
        :key="index"
      >
        <view class="history-content">
          <view>时间：{{ item.time || '--' }}</view>
          <view>坐标：{{ item.lng?.toFixed(6) || '未知' }}, {{ item.lat?.toFixed(6) || '未知' }}</view>
          <view>地址：{{ item.address || '未解析' }}</view>
          <view>上传：{{ item.uploaded ? '成功' : '失败' }}</view>
        </view>
        <button 
          class="delete-btn" 
          @click="deleteHistoryItem(index)"
        >
          删除
        </button>
      </view>
    </view>

    <!-- 其他设置模块保持不变 -->
    <view class="setting-group">
      <text class="group-title">账号设置</text>
      <view class="setting-item" @click="goToAccountSecurity">
        <text>账号与安全</text>
      </view>
      <view class="setting-item" @click="goToChangePassword">
        <text>修改密码</text>
      </view>
      <view class="setting-item" @click="logout" v-if="isLogin">
        <text>退出登录</text>
      </view>
    </view>

    <view class="setting-group">
      <text class="group-title">通知设置</text>
      <view class="setting-item">
        <text>新消息通知</text>
        <switch :checked="newMsgNotify" @change="toggleNewMsgNotify"></switch>
      </view>
      <view class="setting-item">
        <text>订单状态通知</text>
        <switch :checked="orderNotify" @change="toggleOrderNotify"></switch>
      </view>
      <view class="setting-item">
        <text>推送通知</text>
        <switch :checked="pushNotify" @change="togglePushNotify"></switch>
      </view>
    </view>

    <view class="setting-group">
      <text class="group-title">界面设置</text>
      <view class="setting-item" @click="changeTheme">
        <text>主题模式</text>
        <text>{{ theme === 'light' ? '浅色模式' : '深色模式' }}</text>
      </view>
      <view class="setting-item" @click="adjustFontSize">
        <text>字体大小</text>
        <text>{{ fontSize }} 号</text>
      </view>
    </view>

    <view class="setting-group">
      <text class="group-title">隐私与权限</text>
      <view class="setting-item" @click="checkLocationPermission">
        <text>位置权限</text>
      </view>
      <view class="setting-item" @click="clearCache">
        <text>清除缓存</text>
        <text>{{ cacheSize }}</text>
      </view>
      <view class="setting-item" @click="openPrivacyPolicy">
        <text>隐私政策</text>
      </view>
    </view>

    <view class="setting-group">
      <text class="group-title">关于应用</text>
      <view class="setting-item" @click="showAppInfo">
        <text>应用版本</text>
        <text>v1.0.0</text>
      </view>
      <view class="setting-item" @click="checkUpdate">
        <text>检查更新</text>
      </view>
      <view class="setting-item" @click="goToFeedback">
        <text>意见反馈</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 定位核心状态与数据（新增上传相关字段）
      isTracking: false,
      status: "",
      statusTip: "点击开始追踪位置",
      currentLocation: {},
      lastUpdateTime: "",
      uploadHistory: [],
      baiduAK: "QRlTU79HkzFsBFB3x8FrBve4OulDFqQT",
      trackTimer: null,
      lastTrackedLocation: null,
      lastDistance: 0,
      isGettingLocation: false,
      uploadStatus: "未上传", // 新增：接口上传状态
      employeeId: null, // 新增：接单员ID（从登录信息获取）
      apiBaseUrl: "http://localhost:6013/order-client/api", // 后端接口基础地址

      // 其他设置项数据
      isLogin: true,
      newMsgNotify: true,
      orderNotify: true,
      pushNotify: true,
      theme: 'light',
      fontSize: 16,
      cacheSize: '0.5MB'
    };
  },
  onLoad() {
    // 页面加载时获取接单员ID（实际项目中从登录信息中获取）
    this.employeeId = uni.getStorageSync('employeeId') || 1; // 示例ID，实际应从登录态获取
    this.loadHistoryFromStorage();
    console.log("页面加载完成，接单员ID：", this.employeeId);
  },
  onUnload() {
    this.stopTracking();
  },
  methods: {
    // 1. 距离计算方法（保持不变）
    haversineDistance(lat1, lng1, lat2, lng2) {
      const earthRadius = 6371000;
      const dLat = (lat2 - lat1) * Math.PI / 180;
      const dLng = (lng2 - lng1) * Math.PI / 180;
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
        Math.sin(dLng/2) * Math.sin(dLng/2); 
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
      return earthRadius * c;
    },

    // 2. 坐标系转换（保持不变）
    gcj02ToBd09(lng, lat) {
      const x = lng;
      const y = lat;
      const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
      const theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
      const bdLng = z * Math.cos(theta) + 0.0065;
      const bdLat = z * Math.sin(theta) + 0.006;
      return { lng: bdLng, lat: bdLat };
    },

    // 3. 切换追踪状态（保持不变）
    toggleTracking() {
      console.log("切换追踪状态：", this.isTracking ? "停止" : "开始");
      this.isTracking ? this.stopTracking() : this.startTracking();
    },

    // 4. 开始追踪（保持不变）
    startTracking() {
      // 检查接单员ID是否存在
      if (!this.employeeId) {
        this.status = "error";
        this.statusTip = "未获取到用户信息，请重新登录";
        return;
      }

      this.checkLocationPermission().then(hasPermission => {
        if (hasPermission) {
          this.isTracking = true;
          this.status = "info";
          this.statusTip = "正在监听位置变化...";
          this.getLocationOnce();
          this.trackTimer = setInterval(() => {
            if (!this.isGettingLocation) {
              this.getLocationOnce();
            }
          }, 5000);
        } else {
          this.status = "error";
          this.statusTip = "请授予位置权限后重试";
        }
      });
    },

    // 5. 停止追踪（保持不变）
    stopTracking() {
      this.isTracking = false;
      this.status = "info";
      this.statusTip = "已停止位置监听，点击开始继续";
      if (this.trackTimer) {
        clearInterval(this.trackTimer);
        this.trackTimer = null;
      }
      this.lastDistance = 0;
      this.isGettingLocation = false;
    },

    // 6. 单次获取位置（新增上传逻辑）
    getLocationOnce() {
      this.isGettingLocation = true;
      console.log("开始获取位置...");
      
      uni.getLocation({
        type: "gcj02",
        isHighAccuracy: true,
        timeout: 10000,
        success: (res) => {
          console.log("获取位置成功（GCJ02）：", { lng: res.longitude, lat: res.latitude });
          
          const bdCoord = this.gcj02ToBd09(res.longitude, res.latitude);
          const currentTime = new Date().toLocaleString();
          const currentAccuracy = res.accuracy || 0;
          this.lastDistance = 0;

          if (this.lastTrackedLocation) {
            this.lastDistance = this.haversineDistance(
              this.lastTrackedLocation.lat,
              this.lastTrackedLocation.lng,
              bdCoord.lat,
              bdCoord.lng
            );
            console.log("与上一次位置距离：", this.lastDistance.toFixed(1), "米");
          }

          const shouldUpdate = !this.lastTrackedLocation || (this.lastDistance > 200 && currentAccuracy < 100);
          if (shouldUpdate) {
            // 更新本地位置信息
            this.currentLocation = {
              lng: bdCoord.lng,
              lat: bdCoord.lat,
              accuracy: currentAccuracy,
              address: "解析中..."
            };
            this.lastUpdateTime = currentTime;
            this.lastTrackedLocation = { ...bdCoord };

            // 解析地址
            this.reverseGeocoding(bdCoord.lng, bdCoord.lat);

            // 新增历史记录（添加上传状态字段）
            const newRecord = {
              time: currentTime,
              lng: bdCoord.lng,
              lat: bdCoord.lat,
              address: "解析中...",
              uploaded: false // 初始化为未上传
            };
            this.uploadHistory.unshift(newRecord);
            if (this.uploadHistory.length > 20) this.uploadHistory.pop();
            this.saveHistoryToStorage();

            // 调用接口上传位置信息（核心新增逻辑）
            this.uploadLocationToServer(bdCoord.lng, bdCoord.lat, 0)
              .then(success => {
                if (success) {
                  newRecord.uploaded = true;
                  this.uploadStatus = "上传成功";
                  this.statusTip = `位置更新并上传成功（距离上次${this.lastDistance.toFixed(1)}米）`;
                  this.saveHistoryToStorage(); // 更新历史记录的上传状态
                } else {
                  this.uploadStatus = "上传失败，将重试";
                  this.statusTip = `位置更新成功，但上传失败`;
                  // 失败后3秒重试一次
                  setTimeout(() => {
                    this.uploadLocationToServer(bdCoord.lng, bdCoord.lat, 1);
                  }, 3000);
                }
              });

            this.status = "success";
          } else {
            this.status = "info";
            if (currentAccuracy >= 100) {
              this.statusTip = `定位精度不足（${currentAccuracy}米），暂不更新`;
            } else {
              this.statusTip = `位置未超过200米（当前${this.lastDistance.toFixed(1)}米），暂不更新`;
            }
            this.uploadStatus = "无需上传";
          }
          
          this.isGettingLocation = false;
        },
        fail: (err) => {
          console.error("位置获取失败：", err);
          this.status = "error";
          this.statusTip = "位置获取失败：" + (err.errMsg || "未知错误");
          this.uploadStatus = "定位失败，无法上传";
          if (err.errCode === 10001) this.checkLocationPermission(true);
          this.isGettingLocation = false;
        }
      });
    },

    // 7. 新增：上传位置到后端接口
    uploadLocationToServer(longitude, latitude, retryCount = 0) {
      return new Promise((resolve) => {
        // 检查必要参数
        if (!this.employeeId || !longitude || !latitude) {
          console.error("上传失败：参数不完整", {
            employeeId: this.employeeId,
            longitude,
            latitude
          });
          resolve(false);
          return;
        }

        this.uploadStatus = "上传中...";
        console.log(`开始上传位置（第${retryCount + 1}次）：`, {
          employeeId: this.employeeId,
          longitude,
          latitude
        });

        uni.request({
          url: `${this.apiBaseUrl}/employeeInfo/updateLocation`,
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded" // 匹配后端form参数要求
          },
          data: {
            employeeId: this.employeeId,
            longitude: longitude,
            latitude: latitude
          },
          success: (res) => {
            console.log("上传接口返回：", res.data);
            // 根据后端返回结构判断是否成功（假设成功时code为0或success为true）
            const isSuccess = res.data && res.data.code === 0;
            if (isSuccess) {
              this.uploadStatus = "上传成功";
              resolve(true);
            } else {
              this.uploadStatus = `上传失败：${res.data?.message || "未知错误"}`;
              // 最多重试2次
              if (retryCount < 2) {
                setTimeout(() => {
                  this.uploadLocationToServer(longitude, latitude, retryCount + 1);
                }, 3000);
              }
              resolve(false);
            }
          },
          fail: (err) => {
            console.error("上传接口请求失败：", err);
            this.uploadStatus = `网络错误：${err.errMsg}`;
            // 最多重试2次
            if (retryCount < 2) {
              setTimeout(() => {
                this.uploadLocationToServer(longitude, latitude, retryCount + 1);
              }, 3000);
            }
            resolve(false);
          }
        });
      });
    },

    // 8. 百度逆地理编码（保持不变）
    reverseGeocoding(lng, lat) {
      if (!lng || !lat || isNaN(lng) || isNaN(lat)) {
        console.error("经纬度无效：", lng, lat);
        this.currentLocation.address = "坐标错误";
        return;
      }

      uni.request({
        url: "https://api.map.baidu.com/reverse_geocoding/v3/",
        method: "GET",
        data: {
          ak: this.baiduAK,
          output: "json",
          location: `${lat},${lng}`,
          coordtype: "bd09ll",
          extensions: "base"
        },
        success: (res) => {
          if (res.data && res.data.status === 0) {
            if (res.data.result?.formatted_address) {
              const province = res.data.result.addressComponent?.province || "";
              const city = res.data.result.addressComponent?.city || "";
              const district = res.data.result.addressComponent?.district || "";
              const street = res.data.result.addressComponent?.street || "";
              
              this.currentLocation.address = `${province}${city}${district}${street}`;
              
              if (this.uploadHistory.length > 0) {
                this.uploadHistory[0].address = this.currentLocation.address;
                this.saveHistoryToStorage();
              }
              
              this.status = "success";
              this.statusTip = `地址解析成功（距离上次${this.lastDistance.toFixed(1)}米）`;
            } else {
              this.currentLocation.address = "未获取到详细地址";
              this.status = "warning";
              this.statusTip = "地址信息不完整";
            }
          } else {
            this.currentLocation.address = "解析失败";
            this.status = "warning";
            this.statusTip = `API错误(${res.data?.status})：${res.data?.message || "未知错误"}`;
          }
        },
        fail: (err) => {
          console.error("百度API请求失败：", err);
          this.currentLocation.address = "网络请求失败";
          this.status = "error";
          this.statusTip = "请检查网络连接";
        }
      });
    },

    // 9. 其他方法保持不变（权限检查、历史记录管理等）
    checkLocationPermission(showDialog = false) {
      return new Promise((resolve) => {
        uni.getSetting({
          success: (res) => {
            if (res.authSetting?.['scope.userLocation']) {
              resolve(true);
            } else {
              if (showDialog) {
                uni.showModal({
                  title: "需要位置权限",
                  content: "请开启位置权限以获取准确地址",
                  confirmText: "去设置",
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      uni.openSetting({
                        success: (settingRes) => {
                          resolve(settingRes.authSetting['scope.userLocation'] || false);
                        }
                      });
                    } else {
                      resolve(false);
                    }
                  }
                });
              } else {
                uni.authorize({
                  scope: 'scope.userLocation',
                  success: () => resolve(true),
                  fail: () => resolve(false)
                });
              }
            }
          },
          fail: () => resolve(false)
        });
      });
    },

    saveHistoryToStorage() {
      const validHistory = this.uploadHistory.filter(item => item.lng && item.lat);
      uni.setStorageSync("uploadHistory", validHistory);
    },
    loadHistoryFromStorage() {
      const history = uni.getStorageSync("uploadHistory") || [];
      this.uploadHistory = history.filter(item => item.lng && item.lat);
    },

    deleteHistoryItem(index) {
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这条记录吗？",
        confirmText: "删除",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            this.uploadHistory.splice(index, 1);
            this.saveHistoryToStorage();
            uni.showToast({ title: "删除成功", icon: "success", duration: 1500 });
          }
        }
      });
    },

    clearAllHistory() {
      uni.showModal({
        title: "确认清空",
        content: "确定要删除所有历史记录吗？此操作不可恢复。",
        confirmText: "清空",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            this.uploadHistory = [];
            this.saveHistoryToStorage();
            uni.showToast({ title: "已清空所有记录", icon: "success", duration: 1500 });
          }
        }
      });
    },

    // 其他设置项方法保持不变
    goToAccountSecurity() {
      uni.navigateTo({ url: "/pages/setting/accountSecurity" });
    },
    goToChangePassword() {
      uni.navigateTo({ url: "/pages/setting/changePassword" });
    },
    logout() {
      uni.showModal({
        title: "提示",
        content: "确定退出登录吗？",
        success: (res) => {
          if (res.confirm) {
            this.isLogin = false;
            uni.removeStorageSync('employeeId'); // 退出时清除员工ID
            this.employeeId = null;
            uni.showToast({ title: "退出登录成功", icon: "success" });
          }
        }
      });
    },
    toggleNewMsgNotify(e) {
      this.newMsgNotify = e.detail.value;
    },
    toggleOrderNotify(e) {
      this.orderNotify = e.detail.value;
    },
    togglePushNotify(e) {
      this.pushNotify = e.detail.value;
    },
    changeTheme() {
      this.theme = this.theme === "light" ? "dark" : "light";
      uni.showToast({ title: `已切换为${this.theme === 'light' ? '浅色' : '深色'}模式`, icon: "none" });
    },
    adjustFontSize() {
      uni.navigateTo({ url: "/pages/setting/fontSize" });
    },
    clearCache() {
      uni.showLoading({ title: "清除中..." });
      setTimeout(() => {
        this.cacheSize = "0MB";
        uni.hideLoading();
        uni.showToast({ title: "缓存清除成功", icon: "success" });
      }, 1000);
    },
    openPrivacyPolicy() {
      uni.navigateTo({ url: "/pages/setting/privacyPolicy" });
    },
    showAppInfo() {
      uni.showModal({
        title: "应用信息",
        content: "应用名称：XXX\n版本号：v1.0.0\n版权所有 © 2025",
        showCancel: false
      });
    },
    checkUpdate() {
      uni.showToast({ title: "当前已是最新版本", icon: "none" });
    },
    goToFeedback() {
      uni.navigateTo({ url: "/pages/setting/feedback" });
    }
  }
};
</script>

<style scoped>
/* 样式保持不变，仅新增上传状态显示的样式适配 */
.location-upload-module {
  background-color: #fff !important;
  border-radius: 8px !important;
  padding: 15px !important;
  margin-bottom: 20px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
  border: 1px solid #eee !important;
}
.action-btn { margin-bottom: 15px !important; }
.btn-start, .btn-stop {
  width: 100% !important;
  padding: 12px 0 !important;
  border-radius: 5px !important;
  color: #fff !important;
  border: none !important;
  font-size: 16px !important;
  height: auto !important;
}
.btn-start { background-color: #007aff !important; }
.btn-stop { background-color: #ff3b30 !important; }
.status-tip {
  margin-bottom: 15px !important;
  padding: 10px !important;
  border-radius: 5px !important;
  line-height: 1.5 !important;
  font-size: 14px !important;
}
.tip-success { background-color: #dcf8c6 !important; color: #388e3c !important; }
.tip-error { background-color: #ffe5e5 !important; color: #d32f2f !important; }
.tip-info { background-color: #e8f0fe !important; color: #1e88e5 !important; }
.tip-warning { background-color: #fff8e1 !important; color: #f57c00 !important; }
.location-info {
  margin-bottom: 15px !important;
  padding: 10px !important;
  background-color: #f9f9f9 !important;
  border-radius: 5px !important;
  line-height: 1.6 !important;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0 10px !important;
}
.history-title {
  font-weight: bold !important;
  font-size: 16px !important;
  color: #333 !important;
  padding-left: 5px !important;
}
.clear-all-btn {
  background-color: #ff3b30 !important;
  color: white !important;
  border: none !important;
  padding: 5px 10px !important;
  border-radius: 4px !important;
  font-size: 14px !important;
  height: auto !important;
}
.empty-history {
  text-align: center !important;
  padding: 20px !important;
  color: #999 !important;
  font-size: 14px !important;
  background-color: #f9f9f9 !important;
  border-radius: 5px !important;
}
.history-item {
  margin-bottom: 8px !important;
  padding: 10px !important;
  background-color: #f9f9f9 !important;
  border-radius: 5px !important;
  line-height: 1.5 !important;
  font-size: 14px !important;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.history-content { flex: 1; }
.delete-btn {
  background-color: transparent !important;
  color: #ff3b30 !important;
  border: none !important;
  padding: 5px 10px !important;
  font-size: 14px !important;
  height: auto !important;
}

.setting-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 15px;
}
.setting-group {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.group-title {
  display: block;
  padding: 15px;
  font-size: 16px;
  color: #666;
  border-bottom: 1px solid #eee;
}
.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #eee;
}
.setting-item:last-child { border-bottom: none; }
.setting-item text {
  font-size: 15px;
  color: #333;
}
.setting-item switch { transform: scale(0.8); }
</style>
